package keter.lab.grpc.cloud.config;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Created by gulx@neusoft.com on 2019/12/9.
 */
@Configuration
public class Componets {
    @LoadBalanced
    @Primary
    @Bean
    public RestTemplate simple(){
        return new RestTemplate();
    }

    @LoadBalanced
    @Bean("httpClient")
    public  RestTemplate httpClientTemplate(){
        // 使用HttpComponent构造restTemplate客户端
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient());
        // 设置超时时间
        factory.setConnectTimeout(2000);
        factory.setReadTimeout(1000 * 2);
        return new RestTemplate(factory);
    }

    @LoadBalanced
    @Bean("okHttp")
    public  RestTemplate okHttp(){
        OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)      //设置连接超时
            .readTimeout(10, TimeUnit.SECONDS)         //设置读超时
            .writeTimeout(60, TimeUnit.SECONDS)        //设置写超时
            .retryOnConnectionFailure(true)            //是否自动重连
            .connectionPool(
                new ConnectionPool(
                50,    // 10个并发连接
                6,       // 6分钟空闲自动回收
                TimeUnit.MINUTES))
            .build();
        // 使用OkHttp3构造restTemplate客户端
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory(client));
    }

    private HttpClient httpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        //设置整个连接池最大连接数 根据自己的场景决定
        connectionManager.setMaxTotal(200);
        //路由是对maxTotal的细分
        connectionManager.setDefaultMaxPerRoute(50);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(2000)//连接上服务器(握手成功)的时间，超出该时间抛出connect timeout
                .setSocketTimeout(2000) //服务器返回数据(response)的时间，超过该时间抛出read timeout
                .setConnectionRequestTimeout(5000)//从连接池中获取连接的超时时间，超过该时间未拿到可用连接，会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
                .build();
        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .build();
    }
}
